/**
 * Created by cb on 15/3/31.
 */
var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
/**
 * 提示类
 */
var Tips = (function () {
    function Tips(context) {
        this._context = context;
    }
    Tips.prototype.setContext = function (context) {
        this._context = context;
    };
    Tips.prototype.getTips = function () {
        var $_tips = null;
        if (!($_tips = this._context.find('.tips')).length) {
            $_tips = $('<div></div>').addClass('tips');
            this._context.append($_tips);
        }
        return $_tips;
    };
    Tips.prototype.showTips = function () {
        this.getTips().show();
        return this;
    };
    Tips.prototype.hideTips = function () {
        this.getTips().hide();
        return this;
    };
    Tips.prototype.removeTips = function () {
        this.getTips().remove();
        return this;
    };
    Tips.prototype.setTipsMsg = function (message) {
        this.getTips().html(message);
        return this;
    };
    Tips.prototype.appenTipsMsg = function ($_box) {
        this.getTips().append($_box);
        return this;
    };
    return Tips;
})();
var ReviewsAjax = (function (_super) {
    __extends(ReviewsAjax, _super);
    function ReviewsAjax(tips) {
        _super.call(this);
        this._tips = tips;
    }
    ReviewsAjax.prototype.beforeSend = function () {
        var _this = this;
        return function () {
            _this._tips.setTipsMsg('正在加载。。。。').showTips();
        };
    };
    ReviewsAjax.prototype.success = function (data) {
        var _this = this;
        return function (data) {
            _this._tips.hideTips();
            if (data.totalCount == 0) {
                _this._tips.setTipsMsg('暂无评论').showTips();
            }
        };
    };
    ReviewsAjax.prototype.error = function () {
        var _this = this;
        return function () {
            var resert = $("<a href='javascript:;'>请刷新重试</a>").one('click', function () {
                _this.context.http();
            });
            _this._tips.setTipsMsg('加载失败。。。').appenTipsMsg(resert).showTips();
        };
    };
    return ReviewsAjax;
})(BaseAjax);
var RecordAjax = (function (_super) {
    __extends(RecordAjax, _super);
    function RecordAjax() {
        _super.apply(this, arguments);
    }
    RecordAjax.prototype.hasVisibleTable = function () {
        return !$("#P_SalesRecords table:hidden").length;
    };
    RecordAjax.prototype.changeTipsContext = function () {
        this._tips.setContext(this.hasVisibleTable() ? $("#P_SalesRecords table") : $("#P_SalesRecords"));
    };
    RecordAjax.prototype.beforeSend = function () {
        var _this = this;
        return function () {
            _this.changeTipsContext();
            if (_this.context.hasPage()) {
                _this.context.getPage().hide();
            }
            _this._tips.setTipsMsg('正在加载。。。。').showTips();
        };
    };
    RecordAjax.prototype.success = function (data) {
        var _this = this;
        return function (data) {
            _this._tips.hideTips();
            if (_this.context.hasPage()) {
                _this.context.getPage().show();
            }
            if (data.totalCount == 0) {
                _this._tips.setTipsMsg('暂无销售记录').showTips();
            }
        };
    };
    RecordAjax.prototype.error = function () {
        var _this = this;
        return function () {
            _this.changeTipsContext();
            var resert = $("<a href='javascript:;'>请刷新重试</a>").one('click', function () {
                _this.context.http();
            });
            _this._tips.setTipsMsg('加载失败。。。').appenTipsMsg(resert).showTips();
        };
    };
    return RecordAjax;
})(ReviewsAjax);
var ReviewController = (function () {
    function ReviewController(page, ajax, goodsId) {
        this.httpUrl = '';
        this.tabReview();
        this.page = page;
        this.goodsId = goodsId;
        this.page.addObserver(this);
        this._ajax = ajax;
        this._ajax.context = this;
        this.initialization();
    }
    ReviewController.prototype.initialization = function () {
        //移除全部评论
        $("#R_grid dl").remove();
        //移除分页
        this.page.removePage();
        //初始化配置参数
        this.params = { goodsId: this.goodsId, pageNumber: 1 };
    };
    ReviewController.prototype.update = function (page) {
        //移除全部评论
        $("#R_grid dl").remove();
        this.params.pageNumber = page;
        this.http();
    };
    //切换评论
    ReviewController.prototype.tabReview = function () {
        var _this = this;
        $('#R_tabs li').click(function () {
            if ($(this).hasClass('current'))
                return false;
            $('#R_tabs li.current').removeClass('current');
            $(this).addClass('current');
            //初始化
            _this.initialization();
            //获取评论状态 默认全部为undefined
            var reviewType = $(this).attr('reviewType');
            _this.params.grade = reviewType;
            if (typeof reviewType == 'undefined') {
                delete _this.params.grade;
            }
            _this.http();
        });
    };
    ReviewController.prototype.addPage = function (totalNumber, pageSize) {
        this.page.removePage();
        this.page.config(totalNumber, pageSize, this.params.pageNumber);
        $('#R_grid').append(this.page.showPage());
    };
    //把单条数据绑定到模板上
    ReviewController.prototype.bindDataToTmp = function (data) {
    	var tip = '';
    	if(data.score >= 4) {
    		tip = '非常满意';
    	} else if(data.score <= 1) {
    		tip = '很不满意';
    	} else {
    		tip = '基本满意';
    	}
        var sDom = 	 '<dl>'
        			+	'<dt>'
        			+ 		'<div class="m-icon"><img src="/resource/images/default_logo.jpg" ></div>'
        			+		'<div class="m-name" >' + data.userName + '</div>'
        			+ 		'<div class="m-level" >普通会员 </div>'
        			+ 	'</dt>'
        			+ 	'<dd >'
        			+ 		'<div class="reviews-info" >'
        			+ 			'<p class="reviews-starts" ><span class="start sa'+ data.score +'" ></span><span>' + tip + '</span></p>'
        			+ 			'<p class="reviews-time" >'+ data.commentDate +'</p>'
        			+ 		'</div>'
        			+ 		'<div class="reviews-cont" >' + data.content + '</div>'
        			+ 		'<div class="buy-time">购买日期：' + data.buyDate + '</div>'
        			+ 	'</dd>'
        			+ '</dl>';
        return sDom;
    };
    //把多条数据绑定到模板上
    ReviewController.prototype.bindDatasToTmp = function (list) {
        var _this = this;
        var aList = [];
        list.forEach(function (reviewItem) {
            aList.push(_this.bindDataToTmp(reviewItem));
        });
        return aList;
    };
    /**
     * 把数据添加到页面上
     * @param {[type]} list [description]
     */
    ReviewController.prototype.addDomFromList = function (list) {
        var sDom = list.join('');
        $('#R_grid').append(sDom);
    };
    /**
     * 在页面上显示商品评论
     * @param {[type]} data [description]
     */
    ReviewController.prototype.showReview = function (data) {
        this.addDomFromList(this.bindDatasToTmp(data.list));
        this.addPage(data.totalCount, data.pageSize);
    };
    ReviewController.prototype.http = function () {
        var _this = this;
        this._ajax.setConfig({
            method: 'post',
            data: this.params,
            url: this.httpUrl
        });
        this._ajax.http().done(function (data) {
            if (data.totalCount > 0) {
                _this.showReview(data);
            }
        });
    };
    return ReviewController;
})();
var RecordController = (function () {
    function RecordController(page, ajax, goodsId) {
        this.httpUrl = '';
        this.pageSize = 10;
        this.page = page;
        this.page.addObserver(this);
        this._ajax = ajax;
        this._ajax.context = this;
        this.params = {
            goodsId: goodsId,
            pageNumber: 1,
            pageSize: this.pageSize
        };
    }
    RecordController.prototype.addPage = function (totalNumber, pageSize) {
        this.page.config(totalNumber, pageSize);
        if (!this.page._wrap)
            $('.record_page').append(this.page.showPage());
    };
    //清楚销售记录
    RecordController.prototype.cleanRecordRow = function () {
        $('#P_SalesRecords .record-row').remove();
    };
    RecordController.prototype.update = function (pageNum) {
        this.cleanRecordRow();
        this.params.pageNumber = pageNum;
        this.http();
    };
    RecordController.prototype.bindDataToTmp = function (item) {
        var str = "<tr class='record-row'>"
        			+ "<td>" + item.userName + "</td>"
        			+ "<td>" + goodsName + "</td>"
        			+ "<td>" + item.salePrice + "</td>"
        			+ "<td>" + item.quantity + "</td>"
        			+ "<td>" + item.buyDate + "</td>"
        		+ "</tr>";
        return str;
    };
    RecordController.prototype.bindDatasToTmp = function (list) {
        var _this = this;
        var aList = [];
        list.forEach(function (reviewItem) {
            aList.push(_this.bindDataToTmp(reviewItem));
        });
        return aList;
    };
    /**
    * 把数据添加到页面上
    * @param {[type]} list [description]
    */
    RecordController.prototype.addDomFromList = function (list) {
        var sDom = list.join('');
        $('#P_SalesRecords table').show().append(sDom);
    };
    RecordController.prototype.hasPage = function () {
        return !!this.page._wrap;
    };
    RecordController.prototype.getPage = function () {
        return this.page._wrap;
    };
    RecordController.prototype.addPage = function (totalNumber, pageSize) {
        this.page.config(totalNumber, pageSize);
        if (!this.page._wrap)
            $('#P_SalesRecords').append(this.page.showPage());
    };
    RecordController.prototype.showRecord = function (data) {
        this.addDomFromList(this.bindDatasToTmp(data.list));
        this.addPage(data.totalCount, data.pageSize);
    };
    RecordController.prototype.http = function () {
        var _this = this;
        this._ajax.setConfig({
            data: this.params,
            mthod: 'post',
            url: this.httpUrl
        });
        this._ajax.http().done(function (data) {
            if (data.totalCount > 0) {
                _this.showRecord(data);
            }
        });
    };
    return RecordController;
})();
$(function () {
    var $easyzoom = $('.easyzoom').easyZoom(), api = $easyzoom.data('easyZoom');
    // Setup thumbnails example
    $("#P_UlThumb").on("click", "a", function (e) {
        var $this = $(this);
        $("#P_UlThumb li.current").removeClass('current');
        $this.parent().addClass('current');
        e.preventDefault();
        // Use EasyZoom's `swap` method
        api.swap($this.data("standard"), $this.attr("href"));
    });
    //修改数量
    var hpStock = new NumberChange($('.product-stock'));
    hpStock.config.min = 1;
    //加入购物
    $('.product-add-cart').click(function () {
        var num = parseInt($('.product-stock').find('.cart-num').val()), name = $('.hp-detail-hd h1').text(), nId = parseInt($(this).attr('product-id')); // 上品牌id
        var _this = $(this);
        //TODO请求添加购物车  请求前d.show(); 完成后调用 d.close();
        ajax({
            url: base + "/cart/add.jhtml",
            data: {
                goodsId: goodsId,
                num: num
            },
            showError: true,
            cache: false,
            beforeSend:function(){
            },
            success: function(data){
            	productAddCart(_this, num, goodsId, $("li.current").find("img").attr("src"));
            },
            complete:function(){
            }
        });
    });
    //销售记录
    var oBuyRecordController = new RecordController(new PageDom(), new RecordAjax(new Tips($('#P_SalesRecords'))), goodsId);
    oBuyRecordController.httpUrl = base + '/goods/buyRecords.jhtml';
    showIdentityDom();
    //商品详情tabs切换
    $('#P_TabBar li.tab-bar').click(function () {
        if ($(this).hasClass('current'))
            return false;
        $('#P_TabBar li.current').removeClass('current');
        $(this).addClass('current');
        showIdentityDom($(this).attr('show'));
        if ($(this).hasClass('record')) {
            if ($("#P_SalesRecords table:hidden").length)
                oBuyRecordController.http();
        }
        //滚动到对应的位置
        sIdentity = $(this).attr('show');
        var aIdetity = sIdentity.split('-');
        $.each(aIdetity, function (i, index) {
            $('.tabs-cont .tab-c[identity=' + index + ']').show();
        });
        $('html, body').animate({ scrollTop: $('.tabs-cont .tab-c[identity=' + aIdetity[0] + ']').offset().top - 100 }, 300);
    });
    //用户评论
    var oReviewController = new ReviewController(new PageDom(), new ReviewsAjax(new Tips($('#R_grid'))), goodsId);
    oReviewController.httpUrl = base + '/goods/comments.jhtml';
    oReviewController.http();
    //点击按钮滚到对应的位置 并显示想要的内容
    $('.hp-count li').click(function () {
        var nTargetTop = $($(this).attr('scroll')).offset().top;
        $('html, body').animate({ scrollTop: nTargetTop }, 500);
        $('#P_TabBar li[show=' + $(this).attr('show') + ']').trigger('click');
    });
    var nInitTabBartTop = $("#P_TabBar").offset().top;
    $(window).on('scroll', function () {
        if ($(window).scrollTop() > nInitTabBartTop) {
            $('#bar-addCart').addClass('show');
            $("#P_TabBar").css({
                position: 'fixed',
                top: 0
            });
        }
        else {
            $('#bar-addCart').removeClass('show');
            $("#P_TabBar").css({
                position: 'relative'
            });
        }
    });
    $('.addCartActionBtn').click(function (e) {
        e = e || window.event;
        e.stopPropagation();
        if ($('.m-info:hidden').length)
            $('.m-info').show();
        else
            $('.m-info').hide();
    });
    $('.m-info').click(function (e) {
        e = e || window.event;
        e.stopPropagation();
    }).find('.cancel').click(function () {
        $('.m-info').hide();
    });
    $(document).click(function () {
        $('.m-info').hide();
    });

    //到货通知
    $("#tellMeNotice").click(function(){
        var id = $(this).attr('product-id');
        ajax({
            url: base + "/member/hasEmail.jhtml",
            data: {id: id},
            showError: true,
            cache: false,
            success: function (data) {
                oDialog.confirm( '当商品到货的时候将会通过邮件通知您！',
                    function(){
                        if (data) {
                            ajax({
                                url : base + "/member/stocknotice/register.jhtml",
                                data : {goodsId: id},
                                showError : true,
                                cache : false,
                                success : function(data) {
                                    oDialog.prompt(data.content,2000);
                                }
                            });
                        } else {
                            oDialog.confirm("请先完善您的邮箱",
                                function() {
                                    window.open(base + '/member/info.jhtml');
                                }
                            );
                        }
                    }
                );
            }
        });

    });
});
//根据身份设别去显示对应得内容
function showIdentityDom(sIdentity) {
    //如果不传入身份设别id 则用去取默认的showIdentityDom
    if (arguments.length == 0)
        sIdentity = $('#P_TabBar li.current').attr('show');
    var aIdetity = sIdentity.split('-');
    $('.cb-style1-right.click-tabs .tabs-cont .tab-c').hide();
    aIdetity.forEach(function (i) {
        $('.tabs-cont .tab-c[identity=' + i + ']').show();
    });
}


//加入浏览记录
function addHistory(id, domain) {
    var id = id + '';
    var _hgicn = $.cookie('_hgicn');
    _hgicn = !_hgicn  ? [] : _hgicn.replace(/^,|,$/g,'').split(',');
    var	index = _hgicn.indexOf(id);
    if( ~index ) {
        _hgicn.splice(index,1);
    }
    _hgicn.unshift(id);
    if (_hgicn.length >  10 ) {
        _hgicn.pop();
    }
    $.cookie('_hgicn', ',' + _hgicn.join(',') + ',', {expires: 60*60*24*7, path: '/', domain: domain});
}

function addFavorite(id){
	if(!id){
		return;
	}
	ajax({
        url: base + "/member/addFavorite.jhtml",
        data: {goodsIds: id},
        showError: true,
        cache: false,
        success: function (data) {
            oDialog.prompt("商品收藏成功");
            $(".hp-collect").addClass("hp-collected");
            $(".hp-collect").html("已收藏");
            $(".hp-collect").prop("href", "javascript:;");
        }
    });
}
